<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>融道视频脱敏系统</title>
  <style>
    body { font-family: Arial, sans-serif; background: #f4f4f4; margin: 0; }
    h1 { text-align: center; font-size: 36px; margin: 20px 0; color: #333; }
    
    /* 上传区 */
    .upload-card { background: #fff; width: 90%; max-width: 700px; margin: 40px auto; padding: 40px 20px; border-radius: 10px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); text-align: center; position: relative; border: 2px dashed #ccc; transition: border-color .3s; }
    .upload-card.dragover { border-color: #4a90e2; background: #f0f8ff; }
    .upload-card input[type="file"] { display: none; }
    .upload-card label { padding: 12px 24px; background: #ccc; color: #444; border-radius: 5px; cursor: pointer; transition: background .3s; }
    .upload-card label:hover { background: #bbb; }
    .upload-card .hint { margin-top: 12px; font-size: 14px; color: #666; }
    #startBtn { position: absolute; bottom: 20px; right: 20px; padding: 12px 24px; font-size: 16px; color: #fff; background: #4a90e2; border: none; border-radius: 5px; cursor: pointer; transition: background .3s; }
    #startBtn:disabled { background: #ccc; cursor: not-allowed; }
    #startBtn:hover:not(:disabled) { background: #357ab7; }

    /* 敏感词列表 */
    .lists-container { display: flex; gap: 20px; width: 90%; max-width: 918px; margin: 20px auto; }
    .kw-list { flex: 1; background: #fff; border-radius: 10px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); display: flex; flex-direction: column; max-height: 480px; }
    .kw-list-header { position: sticky; top: 0; background: #fff; padding: 16px; border-bottom: 1px solid #e0e0e0; display: flex; align-items: center; justify-content: space-between; z-index:1; }
    .kw-list-header h2 { margin: 0; font-size: 18px; color: #333; }
    .kw-list-header button { font-size: 14px; padding: 4px 8px; border: 1px solid #ccc; border-radius: 4px; background: #f9f9f9; cursor: pointer; }
    .kw-list ul { list-style: none; margin: 0; padding: 12px 20px; overflow-y: auto; flex:1; }
    .kw-list li { display: flex; align-items: center; padding: 8px 12px; margin-bottom: 8px; border-radius: 6px; transition: background .2s; }
    .kw-list li:hover { background: #f0f8ff; }
    .kw-list li input[type="checkbox"] { width: 20px; height: 20px; margin-right: 12px; cursor: pointer; }
    .kw-list li label { flex:1; font-size:16px; color:#444; }
    .play-btn { margin-left: 8px; width:28px; height:28px; border:none; background:#e67e22; color:#fff; border-radius:50%; line-height:28px; text-align:center; font-weight:bold; cursor:pointer; transition:background .3s; }
    .play-btn:hover { background:#d35400; }
    #add-silence { padding:12px 20px; background:#fafafa; border-top:1px solid #e0e0e0; display:flex; }
    #add-silence input { flex:1; padding:6px; font-size:14px; margin-right:8px; }
    #add-silence button { padding:6px 12px; font-size:14px; background:#34b233; color:#fff; border:1px solid #34b233; border-radius:4px; cursor:pointer; }

    /* 提示框 */
    .message-box { display:none; width:90%; max-width:700px; margin:10px auto; padding:16px; border-radius:8px; }
    .queued-box { background:#fff3cd; border:1px solid #ffeeba; color:#856404; display:flex; align-items:center; }
    .processing-box { background:#d1ecf1; border:1px solid #bee5eb; color:#0c5460; display:flex; flex-direction:column; }
    .processing-box span { margin-top:8px; font-size:14px; }
    .done-box { background:#d4edda; border:1px solid #c3e6cb; color:#155724; display:flex; justify-content:space-between; align-items:center; }
    .done-box a { padding:8px 16px; background:#28a745; color:#fff; border-radius:4px; text-decoration:none; }
    .done-box a:hover { background:#218838; }

    /* 已脱敏视频列表 */
    .output-section { width:90%; max-width:918px; margin:20px auto; }
    .output-section h2 { font-size:18px; color:#333; margin-bottom:8px; }
    .output-section .hint { font-size:14px; color:#666; margin-bottom:12px; }
    .output-list { display:grid; grid-template-columns:repeat(auto-fill,minmax(240px,1fr)); gap:16px; }
    .output-card { background:#fff; border-radius:8px; padding:12px; box-shadow:0 2px 6px rgba(0,0,0,0.1); display:flex; flex-direction:column; }
    .output-card span { font-size:14px; color:#333; margin-bottom:8px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    .output-card a { font-size:14px; color:#4a90e2; text-decoration:none; margin-top:auto; align-self:flex-end; }
    .output-card a:hover { text-decoration:underline; }

    @keyframes spin { to { transform:rotate(360deg); } }
    .spinner { width:20px; height:20px; border:3px solid currentColor; border-top-color:transparent; border-radius:50%; animation:spin 1s linear infinite; margin-right:8px; }
  </style>
</head>
<body>
  <h1>融道视频脱敏系统</h1>

  <div class="upload-card" id="uploadCard">
    <input type="file" id="fileInput" accept="video/*">
    <label for="fileInput" id="fileLabel">点击或拖拽视频文件到此处</label>
    <div class="hint">处理时长：1分钟视频需要处理3分钟，请耐心等待。</div>
    <button id="startBtn">开始脱敏</button>
  </div>

  <!-- 提示框 -->
  <div class="message-box queued-box" id="queuedBox">
    <div class="spinner" style="color:#856404;"></div>
    <span id="queuedText"></span>
  </div>
  <div class="message-box processing-box" id="procBox">
    <div class="spinner" style="color:#0c5460;"></div>
    <strong id="procTitle"></strong>
    <span id="procText"></span>
  </div>
  <div class="message-box done-box" id="doneBox">
    <span>脱敏完成！</span>
    <a id="downloadBtn" href="#" download>下载</a>
  </div>

  <div class="lists-container">
    <!-- 敏感词替换列表 -->
    <div class="kw-list" id="replace-list">
      <div class="kw-list-header">
        <h2>敏感词替换列表</h2>
        <button id="rep-toggle">全选/全不选</button>
      </div>
      <ul>
        {% for item in kw_items %}
        {% set bad = item.display.split('-',1)[0] %}
        <li>
          <input type="checkbox" class="rep-cb" id="rep-{{ loop.index }}" value="{{ bad }}">
          <label for="rep-{{ loop.index }}">{{ loop.index }}. {{ item.display }}</label>
          <button class="play-btn" onclick="playKw('{{ item.file }}')">▶</button>
        </li>
        {% endfor %}
      </ul>
    </div>
    <!-- 敏感词消音列表 -->
    <div class="kw-list" id="silence-list">
      <div class="kw-list-header">
        <h2>敏感词消音列表</h2>
        <button id="sil-toggle">全选/全不选</button>
      </div>
      <ul id="silence-ul">
        {% for item in kw_items %}
        {% set bad = item.display.split('-',1)[0] %}
        <li>
          <input type="checkbox" class="sil-cb" id="sil-{{ loop.index }}" value="{{ bad }}">
          <label for="sil-{{ loop.index }}">{{ loop.index }}. {{ bad }}</label>
        </li>
        {% endfor %}
      </ul>
      <div id="add-silence">
        <input type="text" id="new-silence" placeholder="添加新敏感词">
        <button id="add-sil-btn">添加</button>
      </div>
    </div>
  </div>

  <!-- 最近已脱敏视频部分 -->
  <div class="output-section">
    <h2>最近已脱敏的视频</h2>
    <div class="hint">仅显示最近三天脱敏的视频</div>
    <div class="output-list" id="outputList">
      {% for vid in processed_videos %}
      <div class="output-card">
        <span>{{ vid.created_at }}</span>
        <span>{{ vid.name }}</span>
        <a href="{{ vid.url }}" download>下载</a>
      </div>
      {% endfor %}
      {% if processed_videos|length == 0 %}
      <div style="grid-column:1/-1;text-align:center;color:#666;">
        暂无最近处理记录
      </div>
      {% endif %}
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', () => {
      ['queuedBox','procBox','doneBox'].forEach(id => document.getElementById(id).style.display = 'none');
      document.querySelectorAll('.rep-cb').forEach(cb => cb.checked = true);
    });

    // 拖拽 & 文件选择
    const uploadCard = document.getElementById('uploadCard'),
          fileInput  = document.getElementById('fileInput'),
          fileLabel  = document.getElementById('fileLabel');
    ['dragenter','dragover'].forEach(e => uploadCard.addEventListener(e, ev => {
      ev.preventDefault(); uploadCard.classList.add('dragover');
    }));
    ['dragleave','drop'].forEach(e => uploadCard.addEventListener(e, ev => {
      ev.preventDefault(); uploadCard.classList.remove('dragover');
    }));
    uploadCard.addEventListener('drop', ev => {
      if (ev.dataTransfer.files.length) {
        fileInput.files = ev.dataTransfer.files;
        updateFileLabel();
      }
    });
    fileInput.addEventListener('change', updateFileLabel);
    function updateFileLabel() {
      fileLabel.textContent = fileInput.files.length
        ? fileInput.files[0].name
        : '点击或拖拽视频文件到此处';
    }

    // 播放替换音
    function playKw(file) {
      new Audio('/kw/' + file).play();
    }

    // 全选/反选
    function toggleCheckbox(sel) {
      const cbs = document.querySelectorAll(sel),
            all = Array.from(cbs).every(cb => cb.checked);
      cbs.forEach(cb => cb.checked = !all);
    }
    document.getElementById('rep-toggle').onclick = () => toggleCheckbox('.rep-cb');
    document.getElementById('sil-toggle').onclick = () => toggleCheckbox('.sil-cb');

    // 添加新消音关键词
    const ulSil = document.getElementById('silence-ul'),
          inputSil = document.getElementById('new-silence'),
          addBtn   = document.getElementById('add-sil-btn');
    addBtn.onclick = addSilence;
    inputSil.onkeydown = e => { if (e.key === 'Enter') addSilence(); };
    function addSilence() {
      const val = inputSil.value.trim(); if (!val) return;
      const idx = ulSil.children.length + 1;
      const li = document.createElement('li');
      li.innerHTML = `
        <input type="checkbox" class="sil-cb" id="sil-new-${idx}" value="${val}" checked>
        <label for="sil-new-${idx}">${idx}. ${val}</label>
      `;
      ulSil.appendChild(li);
      inputSil.value = '';
      ulSil.scrollTop = ulSil.scrollHeight;
    }

    // 提交 & 排队/轮询
    const startBtn   = document.getElementById('startBtn'),
          queuedBox   = document.getElementById('queuedBox'),
          queuedText  = document.getElementById('queuedText'),
          procBox     = document.getElementById('procBox'),
          procTitle   = document.getElementById('procTitle'),
          procText    = document.getElementById('procText'),
          doneBox     = document.getElementById('doneBox'),
          downloadBtn = document.getElementById('downloadBtn'),
          outputList  = document.getElementById('outputList');

    startBtn.onclick = async () => {
      if (!fileInput.files.length) return alert('请先选择视频文件');
      const replace_list = Array.from(document.querySelectorAll('.rep-cb:checked')).map(cb=>cb.value),
            silence_list = Array.from(document.querySelectorAll('.sil-cb:checked')).map(cb=>cb.value);
      if (!replace_list.length && !silence_list.length) return alert('请至少选择一个敏感词');

      const form = new FormData();
      form.append('file', fileInput.files[0]);
      form.append('replace', JSON.stringify(replace_list));
      form.append('silence', JSON.stringify(silence_list));

      startBtn.disabled      = true;
      queuedBox.style.display = 'flex';
      procBox.style.display   = 'none';
      doneBox.style.display   = 'none';

      const res = await fetch('/process', { method:'POST', body:form });
      const { job_id, position } = await res.json();
      queuedText.textContent = `正在排队… 前面还有 ${position + 1} 个`;

      const poll = async () => {
        const r = await fetch(`/status/${job_id}`), s = await r.json();
        if (s.status === 'queued') {
          queuedBox.style.display = 'flex';
          queuedText.textContent = `正在排队… 前面还有 ${s.position + 1} 个`;
        }
        else if (s.status === 'processing') {
          queuedBox.style.display = 'none';
          procBox.style.display   = 'flex';
          procTitle.textContent   = '处理中…';
          procText.textContent    = '预计：1分钟视频需要处理 3分钟';
        }
        else if (s.status === 'done') {
          procBox.style.display   = 'none';
          doneBox.style.display   = 'flex';
          downloadBtn.href        = s.url;
          downloadBtn.download    = s.filename;
          startBtn.disabled       = false;

          // 动态插入到已脱敏列表
          const now = new Date();
          const pad = n => String(n).padStart(2,'0');
          const ts = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
          const card = document.createElement('div');
          card.className = 'output-card';
          card.innerHTML = `
            <span>${ts}</span>
            <span>${s.filename}</span>
            <a href="${s.url}" download>下载</a>
          `;
          outputList.insertBefore(card, outputList.firstChild);

          // 清理三天前
          const cutoff = Date.now() - 3*24*3600*1000;
          Array.from(outputList.querySelectorAll('.output-card')).forEach(c => {
            const dateText = c.querySelector('span').textContent.replace(' ', 'T');
            if (new Date(dateText).getTime() < cutoff) outputList.removeChild(c);
          });
        }
        else if (s.status === 'failed') {
          queuedBox.style.display = 'none';
          procBox.style.display   = 'none';
          alert('处理失败：' + s.error);
          startBtn.disabled = false;
        }
        if (s.status==='queued' || s.status==='processing') setTimeout(poll,2000);
      };
      poll();
    };
  </script>
</body>
</html>
